﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BookExchange.Business;
using BookExchange.CustomClass.Base;
using BookExchange.ODataService;
using BookExchange.Configuration;

namespace BookExchange
{
    public partial class Edit : BasePage
    {
        Request post;
        RequestBusiness requestBus;
        CategoryBusiness catBus;
        public Edit()
            : base()
        {
            requestBus = new RequestBusiness();
            catBus = new CategoryBusiness();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsUserAuthenticated)
            {
                this.RedirectToLoginPage(null, Request.RawUrl);
                return;
            }
            ShowStatus();

            if (!IsPostBack)
            {
                PopulateControls();
                CheckRequest();
            }
            
        }
        private void ShowStatus()
        {
            List<ListItem> items = new List<ListItem>();
            items.Add(new ListItem("Còn hàng", "S"));
            items.Add(new ListItem("Đã bán", "F"));
           // ddlStatus.Items.AddRange(items.ToArray());
           // ddlStatus.Items.FindByText(ddlStatus.SelectedItem.Text).Selected = true;
        }
        private void CheckRequest()
        {
            //Request type = new Request();
            
            if (post!=null )
            {
                if (post.RequestType == RequestType.Request)
                {
                    txtPrice1.Visible = false;
                    txtPrice1.Visible = false;
                }
            }
        }
        
        private ODataService.Request GetRequestFromGUI()
        {
            ODataService.Request post = null;
            if (string.IsNullOrEmpty( lblId.Text))
            {
                return post;
            }

            post = requestBus.GetRequestByCode(Convert.ToInt32(lblId.Text));

            post.CategoryCode = Convert.ToInt32(ddlCategory.SelectedValue);
            post.BookName = txtBookName.Text;
            post.Description = txtDescription.Text;
            //post.Status = ddlStatus.SelectedValue;
            post.Quantity = Convert.ToInt32(txtQuantity.Text);
            post.Price1 = Convert.ToDecimal(txtPrice1.Text);
            post.Price2 = Convert.ToDecimal(txtPrice2.Text);
            post.Contact = txtContact.Text;
            post.ExchangePlace = txtExP.Text;
            post.BookUrl = txtBookUrl.Text;
            post.LastModified = DateTime.Now;
            return post;
        }

        private void PopulateCategory(List<Category> categoryList)
        {
            
            ddlCategory.DataValueField = "CategoryCode";
            ddlCategory.DataTextField = "Description";
            ddlCategory.DataSource = categoryList;
            ddlCategory.DataBind();
        }

        private void SetData(ODataService.Request post)
        {
            lblId.Text = post.RequestCode.ToString();
            ddlCategory.SelectedValue = post.CategoryCode.ToString();
            //ddlMember.SelectedValue = post.MemberCode.ToString();
            txtBookName.Text = post.BookName.ToString();
            txtDescription.Text = post.Description.ToString();
            //ddlStatus.SelectedValue = post.Status.ToString();
            txtQuantity.Text = post.Quantity.ToString();
            txtPrice1.Text = post.Price1.ToString();
            txtPrice2.Text = post.Price2.ToString();
            txtContact.Text = post.Contact.ToString();
            txtExP.Text = post.ExchangePlace.ToString();
            txtBookUrl.Text = post.BookUrl.ToString();
            //txtDate.Text = post.CreatingDate.ToString();
        }

        private void ResetForm()
        {
            ddlCategory.SelectedIndex = 0;
            txtDescription.Text = "";
            //ddlStatus.SelectedIndex = 0;
            txtQuantity.Text = "";
            txtPrice1.Text = "";
            txtPrice2.Text = "";
            txtContact.Text = "";
            txtExP.Text = "";
            txtBookName.Text = "";
            txtBookUrl.Text = "";
            lblImage.Text = "";
            //txtDate.Text = "";
        }

        private void PopulateControls()
        {
            string cid = Request.QueryString["c"] ?? "";
            if (string.IsNullOrEmpty(cid))
            {
                return;
            }

            post = requestBus.GetRequestByCode(Convert.ToInt32(cid));
            var categoryList = catBus.GetCategoryList();
            if (post == null)
            {
                Response.Redirect("Post.aspx");
            }

            PopulateCategory(categoryList);
            SetData(post);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }
            
            ODataService.Request post = GetRequestFromGUI();
            if (post == null)
            {
                //Log this errror
                return;
            }

            requestBus.Update(post);
            RedirecToDetailPage(post.RequestCode);

            //Upload
            if (fileUploadBook.HasFile)
            {
                if (IsImageFile(fileUploadBook.FileName))
                {
                    ODataService.Image newBookImage = new ODataService.Image();
                    newBookImage.CreatingDate = DateTime.Now;
                    newBookImage.ID = Guid.NewGuid();
                    newBookImage.LastModified = DateTime.Now;
                    newBookImage.RequestCode = post.RequestCode;
                    newBookImage.Url = string.Format("{0}{1}",
                        "http://bookexchange.travianoverview.com/ImgFiles/",
                        newBookImage.ID.ToString());

                    fileUploadBook.SaveAs(Server.MapPath(AppConfiguration.Instance.ImageFolder) + fileUploadBook.FileName);
                    lblImage.Text = "Upload thanh cong";
                }
                else
                {
                    lblImage.Text = "Loai file khong hop le";
                }
            }
        }

        private bool IsImageFile(string FileName)
        {
            string fileExtension = Path.GetExtension(FileName);

            List<string> imageFileExtensions = new List<string> { ".gif", ".png", ".jpeg", ".jpg" };

            return imageFileExtensions.Exists(item => item.Equals(fileExtension));
        }

    }
}